import 'dart:io';

import 'package:flutter/services.dart';

enum KeyCode {
  VOLUME_DOWN,
  VOLUME_UP
}

/// In Android, must use [KeyListenerActivity] or [class * extends KeyListenerActivity]
/// In ohos, must use [KeyListenerAbility] or [class * extends KeyListenerAbility]
class KeyListener {

  MethodChannel? _channel;
  ValueChanged<KeyCode>? _onKeyDown;
  ValueChanged<KeyCode>? _onKeyUp;

  /// in ohos,just [onKeyDown] can use
  void init(List<KeyCode> keys, {ValueChanged<KeyCode>? onKeyDown, ValueChanged<KeyCode>? onKeyUp}) {
    this._onKeyDown = onKeyDown;
    this._onKeyUp = onKeyUp;
    _channel = MethodChannel('plugins.flutter.io/key_listener');
    _channel!.setMethodCallHandler((call) async {
      if("onKeyUp" == call.method) {
        switch(call.arguments) {
          case 0 : this._onKeyUp?.call(KeyCode.VOLUME_DOWN); break;
          case 1 : this._onKeyUp?.call(KeyCode.VOLUME_UP); break;
        }
      } else if("onKeyDown" == call.method) {
        switch(call.arguments) {
          case 0 : this._onKeyDown?.call(KeyCode.VOLUME_DOWN); break;
          case 1 : this._onKeyDown?.call(KeyCode.VOLUME_UP); break;
        }
      }
    });
    _channel!.invokeMethod("initialize", keys.map((e) => e.index).toList());
  }

  void dispose() {
    _channel?.invokeMethod("dispose");
    _channel?.setMethodCallHandler(null);
  }
}